#include "stdafx.h"
#include "./winfile.h"

const wchar_t * cfileMode[] = {L"rb", L"wb", L"ab", L"rb+", L"wb+", L"ab+", L"rb", L"rb"};

WinFile::WinFile()
: m_pFile(NULL)
{

}

WinFile::~WinFile()
{

}

bool WinFile::OpenFile(string strPath, IoOpen openflag)
{
	wstring wstrPath;
	StrUtils::UTF8StringToWideString(strPath, wstrPath);

	_wfopen_s(&m_pFile, wstrPath.c_str(), cfileMode[openflag]);

	if (!m_pFile)
	{
		return false;
	}

	return true;
}

void WinFile::CloseFile()
{
	if (!m_pFile)
	{
		return;
	}

	fclose(m_pFile);
}

size_t WinFile::ReadFile(byte* buffer, size_t size)
{
	if (!m_pFile)
	{
		return 0;
	}

	if (!buffer)
	{
		//get size
		fseek(m_pFile, 0L, SEEK_END); 
		size_t length = ftell(m_pFile); 
		fseek(m_pFile, 0, SEEK_SET); 

		return length;
	}

	return fread(buffer, 1, size, m_pFile);
}

size_t WinFile::WriteFile(const byte* buffer, size_t size)
{
	if (!m_pFile)
	{
		return 0;
	}

	return fwrite(buffer, 1, size, m_pFile);
}

long WinFile::SeekFile(long offset, IoSeek origin)
{
	return fseek(m_pFile, offset, origin);
}

long WinFile::TellFile()
{
	return ftell(m_pFile);
}

bool WinFile::GetFolderFiles(string strDir, vector<string>& filenams)
{
	wstring wstrDir;
	StrUtils::UTF8StringToWideString(strDir, wstrDir);

	wstrDir += L"*";

	WIN32_FIND_DATA wfd;
	HANDLE hFile = ::FindFirstFile(wstrDir.c_str(), &wfd);
	do 
	{
		if (INVALID_HANDLE_VALUE == hFile)
		{
			return false;
		}

		if (wcscmp(wfd.cFileName, L".") == 0 || wcscmp(wfd.cFileName, L"..") == 0)
		{
			continue;
		}

		if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			string strFileName;
			StrUtils::WideStringToUTF8String(wfd.cFileName, strFileName);

			filenams.push_back(strFileName);
		}		

	} while (::FindNextFile(hFile, &wfd));

	::FindClose(hFile);

	return true;
}